package com.example.demo.service;

import com.example.demo.config.TtlCache;
import com.example.demo.entity.Book;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class BookService {

    private final CacheManager cacheManager;

    public BookService(CacheManager cacheManager) {
        this.cacheManager = cacheManager;
    }

    public Book getBookByIsbn(String isbn) {
        // 获取名为 "books" 的缓存
        Cache cache = cacheManager.getCache("books");
        if (cache != null) {
            // 尝试从缓存中获取数据
            Book cachedBook = cache.get(isbn, Book.class);
            if (cachedBook != null) {
                System.out.println("Returning cached book for ISBN: " + isbn);
                return cachedBook;
            }
        }

        // 缓存未命中，从数据源获取数据
        System.out.println("Fetching book from database for ISBN: " + isbn);
        Book book = simulateSlowService(isbn);

        // 将数据放入缓存
        if (cache != null) {
            cache.put(isbn, book);
            // 如需自定义TTL，需先转换为TtlCache
            TtlCache ttlCache = (TtlCache) cache;
            ttlCache.put(isbn, book, 60, TimeUnit.MINUTES);
        }

        return book;
    }

    // 模拟从数据库获取数据的慢速服务
    private Book simulateSlowService(String isbn) {
        try {
            Thread.sleep(2000L); // 模拟2秒延迟
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return new Book(isbn, "Some book title for " + isbn);
    }

    // 手动清除缓存的方法
    public void clearCache() {
        Cache cache = cacheManager.getCache("books");
        if (cache != null) {
            cache.clear();
            System.out.println("Cache cleared");
        }
    }
}    